<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>系统界面</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--    <link href="//unpkg.com/layui@2.9.23/dist/css/layui.css" rel="stylesheet">-->
    <link rel="stylesheet" href="./resource/css/index.css" type="text/css">
    <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css">
    <link rel="stylesheet" href="../web/resource/css/allcss/vehicle.css" type="text/css">
    <link rel="stylesheet" href="resource/layui/css/layui.css">
        <script src="../web/resource/js/echarts.min.js"></script>
</head>
<body>
<!-- 顶部导航栏 -->
<nav class="top-nav">
    <ul >
        <li><button class="nav-btn" id="home">首页</button></li>
        <li><button class="nav-btn" id="basicDossier">基础档案</button></li>
        <li><button class="nav-btn" id="logisticsScheduling">物流调度</button></li>
<!--        <li><button class="nav-btn" id="financeManagement">财务管理</button></li>-->
    </ul>
    <ul class="layui-layout-right">
        <li class="user-menu">
            <button class="nav-btn" id="userMenu">用户菜单 ▼</button>
            <div class="dropdown-content" id="dropdownMenu">
                <button class="dropdown-item" id="uerInfo">个人信息</button>
                <button class="dropdown-item" id="updatePassword">修改密码</button>
                <button class="dropdown-item" id="loginOut">退出登录</button>
            </div>
        </li>
    </ul>
</nav>
<!-- 用户信息弹窗 -->
<div class="modal-mask" id="userInfoModal" style="display:none;">
    <div class="modal-content">
        <h3 class="modal-title">
            用户详情
            <button class="modal-close-btn" onclick="closeUserInfoModal()">×</button>
        </h3>
        <div class="modal-body">
            <div class="detail-section">
                <h4 class="detail-subtitle">基础信息</h4>
                <div class="detail-row">
                    <span class="detail-label">登录账号：</span>
                    <span id="detail-account" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">用户名：</span>
                    <span id="detail-userName" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">性别：</span>
                    <span id="detail-gender" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">邮箱：</span>
                    <span id="detail-email" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">所属部门：</span>
                    <span id="detail-depNm" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">角色：</span>
                    <span id="detail-roleNm" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">创建时间：</span>
                    <span id="detail-createTime" class="detail-value"></span>
                </div>
            </div>
            <div class="detail-section">
                <h4 class="detail-subtitle">操作记录</h4>
                <div id="detail-operationLogs" class="detail-logs">
                    <!-- 操作记录动态加载 -->
                </div>
            </div>
        </div>
        <div class="modal-buttons">
            <button type="button" class="btn-close" onclick="closeUserInfoModal()">关闭</button>
        </div>
    </div>
</div>
<!-- 修改密码弹窗 -->
<div class="modal-mask" id="updatePasswordModal" style="display:none;">
    <div class="modal-content">
        <h3 class="modal-title">
            修改密码
            <button class="modal-close-btn" onclick="closeUpdatePasswordModal()">×</button>
        </h3>
        <form class="modal-form" id="updatePasswordForm" onsubmit="return handlePasswordSubmit(event)">
            <div class="form-item">
                <label>原密码：</label>
                <input type="password" id="oldPwd" required>
            </div>
            <div class="form-item">
                <label>新密码：</label>
                <input type="password" id="newPwd" required>
            </div>
            <div class="form-item">
                <label>确认密码：</label>
                <input type="password" id="confirmPwd" required>
                <div class="error-tip" id="pwdError" style="display:none;">两次输入密码不一致</div>
            </div>
            <div class="modal-buttons">
                <button type="button" class="btn-close" onclick="closeUpdatePasswordModal()">关闭</button>
                <button type="submit" class="btn-submit">提交</button>
            </div>
        </form>
    </div>
</div>
<!-- 左侧导航栏（默认隐藏） -->
<!-- 修改后的左侧导航栏结构 -->
<aside class="left-nav" id="leftNav">
    <ul data-module="basicDossier" class="submenu-group">
        <li>
            <button class="parent-btn" id="systemUserManagement">系统用户管理</button>
            <div class="sub-buttons">
                <button class="left-nav-btn" id="departmentManagement">部门管理</button>
                <button class="left-nav-btn" id="roleManagement">角色管理</button>
                <button class="left-nav-btn" id="userManagement">用户管理</button>
            </div>
        </li>
        <li>
            <button class="parent-btn" id="consignorDossier">委托商档案</button>
            <div class="sub-buttons">
                <button class="left-nav-btn" id="consignorManagement">委托商管理</button>
                <button class="left-nav-btn" id="consignorType">委托商类型</button>
                <button class="left-nav-btn" id="customerCarBrand">委托车品牌</button>
                <button class="left-nav-btn" id="customerCarModel">委托车车型</button>
            </div>
        </li>
        <li>
            <button class="parent-btn" id="supplierDossier">供应商档案</button>
            <div class="sub-buttons">
            <button class="left-nav-btn" id="highwaySupplier">公路供应商</button>
            <button class="left-nav-btn" id="waterwaySupplier">水路供应商</button>
            <button class="left-nav-btn" id="carManager">车辆管理</button>
            <button class="left-nav-btn" id="shipManager">船舶管理</button>
            </div>
        <li>
        <li>
<!--            <button class="parent-btn" id="dealerDossier">经销商档案</button>-->
<!--            <div class="sub-buttons">-->
<!--                <button class="left-nav-btn" id="dealerManagement">经销商管理</button>-->
<!--                <button class="left-nav-btn" id="lineManagement">路线管理</button>-->
<!--            </div>  -->
        <button class="parent-btn" id="lineDossier">线路档案</button>
            <div class="sub-buttons">
<!--                <button class="left-nav-btn" id="dealerManagement">经销商管理</button>-->
                <button class="left-nav-btn" id="lineManagement">路线管理</button>
            </div>
        <li>
        <li>
            <button class="parent-btn" id="addressDossier">地址档案</button>
            <div class="sub-buttons">
<!--                <button class="left-nav-btn" id="addressManagement">经销商管理</button>-->
                <button class="left-nav-btn" id="area">区域管理</button>
            </div>
        <li>
    </ul>
    <ul data-module="logisticsScheduling" class="submenu-group">
        <li>
            <button class="parent-btn" id="planManagement">计划管理</button>
            <div class="sub-buttons">
                <button class="left-nav-btn" id="transportationPlanning">运输计划</button>
                <button class="left-nav-btn" id="transportationcv">委托车计划</button>
            </div>
        </li>
        <li>
            <button class="parent-btn" id="fleetManagement">公路运输管理</button>
            <div class="sub-buttons">
                <button class="left-nav-btn" id="vehicleDeployManagement">车辆调配管理</button>
            </div>
        </li>
        <li>
            <button class="parent-btn" id="shipManagement">水路运输管理</button>
            <div class="sub-buttons">
                <button class="left-nav-btn" id="shipDeployManagement">船舶调配管理</button>
            </div>
        </li>
        <li>
            <button class="parent-btn" id="trackingInfo">在途信息</button>
            <div class="sub-buttons">
                <button class="left-nav-btn" id="deployTracking">委托车跟踪</button>
            </div>
        </li>
    </ul>
<!--    <ul data-module="financeManagement" class="submenu-group">-->
<!--        <li>-->
<!--            <button class="parent-btn" id="financePrice">财务管理</button>-->
<!--            <div class="sub-buttons">-->
<!--                <button class="left-nav-btn" id="revenuePrice">价格设置</button>-->
<!--            </div>-->
<!--            <div class="sub-buttons">-->
<!--                <button class="left-nav-btn" id="spendPrice">支出价格设置</button>-->
<!--            </div>-->
<!--        </li>-->
<!--        <li>-->
<!--            <button class="parent-btn" id="financeledger">台账管理</button>-->
<!--            <div class="sub-buttons">-->
<!--                <button class="left-nav-btn" id="ledgerManagement">台账管理</button>-->
<!--            </div>-->
<!--        </li>-->
<!--    </ul>-->
</aside>

<!-- 内容区域 -->
<main class="content" id="content">
    <!-- 动态加载的内容 -->
</main>

<script>
    // 第三部分JavaScript代码
        const topNavLinks = document.querySelectorAll('.top-nav button');
        const leftNav = document.getElementById('leftNav');
        const leftNavParent = document.querySelectorAll('.parent-btn');
        const content = document.getElementById('content');
        const userMenu = document.getElementById('userMenu');
        const dropdownMenu = document.getElementById('dropdownMenu');

    // 修改后的按钮事件监听
    topNavLinks.forEach(btn => {
        btn.addEventListener('click',function (e){
            const target = e.target.id; // 通过id获取目标标识
            if (target === 'home'){
                leftNav.classList.remove('active');
                content.classList.remove('with-sidebar');
                //重置左侧导航栏激活状态
                document.querySelectorAll('.left-nav .left-nav-btn').forEach(item =>
                    item.classList.remove('active'));
                // 折叠所有功能块
                leftNavParent.forEach(parentBtn => {
                    parentBtn.classList.remove('active-parent');
                    parentBtn.closest('li').classList.remove('active-li');
                });
                loadContent(target)
            }else  if (target === 'userMenu'){
                dropdownMenu.classList.toggle('show-dropdown');
                if (!userMenu.contains(e.target)) {
                    dropdownMenu.classList.remove('show-dropdown');
                }
            }else  if (target === 'uerInfo'){
                // console.log("用户信息")
                UserDetail();
            }
            else  if (target === 'updatePassword'){
                console.log("修改密码")
            }
            else  if (target === 'loginOut'){
                localStorage.removeItem('userData');
                window.location.href = 'http://localhost:9095/chxt/web/login.html'
            } else {
                leftNav.classList.add('active');
                content.classList.add('with-sidebar');

                // 折叠所有功能块
                leftNavParent.forEach(parentBtn => {
                    parentBtn.classList.remove('active-parent');
                    parentBtn.closest('li').classList.remove('active-li');
                });

                // 关键逻辑：切换子菜单组
                document.querySelectorAll('.submenu-group').forEach(group => {
                    group.classList.remove('active-group');
                    if (group.dataset.module === target) {
                        group.classList.add('active-group');
                    }
                });
            }
        })
    });

    // 新增功能块按钮点击监听
    leftNavParent.forEach(btn => {
        btn.addEventListener('click', function(e) {
            const parentLi = e.target.closest('li');

            // 切换激活状态
            const isActive = parentLi.classList.contains('active-li');
            document.querySelectorAll('.active-parent').forEach(item =>
                item.classList.remove('active-parent'));
            document.querySelectorAll('.active-li').forEach(item =>
                item.classList.remove('active-li'));

            if (!isActive) {
                e.target.classList.add('active-parent');
                parentLi.classList.add('active-li');

            }
        });
    });

    // 修改后的左侧导航点击事件（替换原a标签监听）
    document.querySelectorAll('.left-nav .left-nav-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const target = e.target.id;
            loadContent(target);

            // 添加激活状态（参考网页3的点击反馈）
            document.querySelectorAll('.left-nav .left-nav-btn').forEach(item =>
                item.classList.remove('active'));
            e.target.classList.add('active');
        });
    });

    // 点击页面其他区域关闭菜单
    document.addEventListener('click', function(e) {
        if (!userMenu.contains(e.target)) {
            dropdownMenu.classList.remove('show-dropdown');
        }
    });


    document.addEventListener('DOMContentLoaded',async function () {
        // 权限检查
        const userData = JSON.parse(localStorage.getItem('userData'));
        const menuIds = JSON.parse(localStorage.getItem('menuPermissions')) || [];

        if (!userData || !menuIds.length) {
            localStorage.clear();
            window.location.href = 'http://localhost:9095/chxt/web/login.html';
            return;
        }

        // 新增：默认加载首页内容
        loadContent('home'); // 调用首页加载逻辑
        document.getElementById('home').click(); // 同步触发导航按钮状态更新

        // 更新用户菜单显示
        updateUserMenu(userData.empNm);

        // 处理菜单显示
        processMenuVisibility(menuIds);
        // const userData = JSON.parse(localStorage.getItem('userData'));
        // if (userData?.empNm) {
        //     updateUserMenu(userData.empNm);
        // }
        // // 获取所有菜单ID的函数
        // function collectMenuIds(menuData, idList = []) {
        //     menuData.forEach(item => {
        //         idList.push(item.id);
        //         if (item.childList && item.childList.length > 0) {
        //             collectMenuIds(item.childList, idList);
        //         }
        //     });
        //     return idList;
        // }
        // const res = await authFetch('http://localhost:8080/role/seAllMenu', {
        //     method: 'GET',
        //     headers: {'Content-Type': 'application/json'},
        // });
        // const {data: apiData} = await res.json();
        // // console.log(apiData)
        //
        // // 提取所有ID
        // const idsList = collectMenuIds(apiData);
        // console.log('有效菜单ID列表:', idsList);
        //
        // // 处理顶部导航栏
        // document.querySelectorAll('.top-nav button').forEach(btn => {
        //     const shouldShow = idsList.includes(btn.id);
        //
        //     if ( !(btn.id ==='userMenu')  ) {
        //         btn.style.display = shouldShow ? '' : 'none';
        //         // console.log(`顶部按钮 ${btn.id} ${shouldShow ? '显示' : '隐藏'}`);
        //     }
        //
        //     // }
        // });
        //
        // // 处理左侧导航栏（包括所有层级按钮）
        // document.querySelectorAll('.left-nav button').forEach(btn => {
        //     const shouldShow = idsList.includes(btn.id);
        //     btn.style.display = shouldShow ? '' : 'none';
        //
        //     // 自动处理父级容器显示状态
        //     const parentLi = btn.closest('li');
        //     if (parentLi) {
        //         const hasVisibleChild = [...parentLi.querySelectorAll('button')]
        //             .some(childBtn => childBtn.style.display !== 'none');
        //         parentLi.style.display = hasVisibleChild ? '' : 'none';
        //     }
        //
        //     // console.log(`左侧按钮 ${btn.id} ${shouldShow ? '显示' : '隐藏'}`);
        // });
    })

    function processMenuVisibility(menuIds) {
        // 处理顶部导航
        document.querySelectorAll('.top-nav button').forEach(btn => {
            if ( (btn.id !== 'userMenu') && (btn.id !== 'dropdownMenu') &&(btn.id !== 'uerInfo') &&(btn.id !== 'updatePassword')
                && (btn.id !== 'loginOut')) {
                btn.style.display = menuIds.includes(btn.id) ? '' : 'none';
            }
        });

        // 处理左侧导航
        document.querySelectorAll('.left-nav button').forEach(btn => {
            const shouldShow = menuIds.includes(btn.id);
            btn.style.display = shouldShow ? '' : 'none';

            // 处理父级可见性
            const parentLi = btn.closest('li');
            if (parentLi) {
                const hasVisibleChild = [...parentLi.querySelectorAll('button')]
                    .some(child => child.style.display !== 'none');
                parentLi.style.display = hasVisibleChild ? '' : 'none';
            }
        });
    }



    // 用户信息弹窗控制
    function showUserInfoModal() {
        document.getElementById('userInfoModal').style.display = 'flex';
    }

    function closeUserInfoModal() {
        document.getElementById('userInfoModal').style.display = 'none';
    }

    // 点击个人信息按钮事件
    async function UserDetail() {
        try {

            const response = await authFetch('http://localhost:8080/user/userInfo', {
                method: 'GET'
            });

            if (!response.ok) throw new Error('请求失败');

            const result = await response.json();
            if (result.status !== 0) throw new Error(result.message);

            // 填充数据
            document.getElementById('detail-account').textContent = result.data.account || '无';
            document.getElementById('detail-userName').textContent = result.data.userName || '无';
            document.getElementById('detail-gender').textContent =
                result.data.empGender === '0' ? '男' : result.data.empGender === '1' ? '女' : '未知';
            document.getElementById('detail-email').textContent = result.data.email || '无';
            document.getElementById('detail-depNm').textContent = result.data.depNm || '无';
            document.getElementById('detail-roleNm').textContent = result.data.roleNm || '无';
            document.getElementById('detail-createTime').textContent =
                new Date(result.data.createTime).toLocaleString() || '无';

            // 填充操作记录
            const logsContainer = document.getElementById('detail-operationLogs');
            logsContainer.innerHTML = result.data.operateRecordList.length > 0
                ? result.data.operateRecordList.map(log => `
                <div class="log-item">
                     <span>${log.createTime || '无时间'}</span>
                    <span class="log-type">${log.operateType}</span>
                </div>
              `).join('')
                : '暂无操作记录';

            showUserInfoModal();
        } catch (error) {
            console.error('获取用户信息失败:', error);
            alert('获取信息失败: ' + error.message);
        }
    }

    // 点击遮罩关闭
    document.getElementById('userInfoModal').addEventListener('click', (e) => {
        if (e.target.classList.contains('modal-mask')) {
            closeUserInfoModal();
        }
    });


    //修改密码
    // 与委托商弹窗一致的交互模式
    let isPwdModalOpen = false;

    function showUpdatePasswordModal() {
        document.getElementById('updatePasswordModal').style.display = 'flex';
        isPwdModalOpen = true;
        resetPwdForm();
    }

    function closeUpdatePasswordModal() {
        document.getElementById('updatePasswordModal').style.display = 'none';
        isPwdModalOpen = false;
    }

    function resetPwdForm() {
        document.getElementById('updatePasswordForm').reset();
        document.getElementById('pwdError').style.display = 'none';
    }

    function validatePasswords() {
        const newPwd = document.getElementById('newPwd').value;
        const confirmPwd = document.getElementById('confirmPwd').value;
        const errorEle = document.getElementById('pwdError');

        if (newPwd !== confirmPwd) {
            errorEle.style.display = 'block';
            return false;
        }
        errorEle.style.display = 'none';
        return true;
    }

    async function handlePasswordSubmit(e) {
        e.preventDefault();

        if (!validatePasswords()) return;

        try {
            const res = await authFetch('http://localhost:8080/user/updatePassword', {
                method: 'POST',
                body: JSON.stringify({
                    oldPwd: document.getElementById('oldPwd').value,
                    newPwd: document.getElementById('newPwd').value
                })
            });

            const data = await res.json();
            if (data.status !== 0) throw new Error(data.message);

            layui.layer.msg('密码修改成功', {icon: 1});
            closeUpdatePasswordModal();
        } catch (err) {
            layui.layer.msg(err.message, {icon: 2});
            console.error('密码修改失败:', err);
        }
    }

    // 绑定点击事件（保持原有事件绑定风格）
    document.getElementById('updatePassword').onclick = showUpdatePasswordModal;
</script>
<script type="text/javascript" src="./resource/js/index.js"></script>
<script type="text/javascript" src="./resource/layui/layui.js"></script>
<script type="text/javascript" src="./resource/js/login.js"></script>
</body>
</html>